package titt.io.encoding.stringable;

import java.net.URLDecoder;

import titt.config.ValueConfig;
import titt.io.encoding.Decoder;
import titt.type.Type;
import titt.type.Types;
import titt.util.Bytes;

public class AsStringDecoder implements Decoder {

	@Override
	public Object decode(Type t, byte[] enc) {
		try {
			String raw = Bytes.asString(enc);
			String str = URLDecoder.decode(raw, ValueConfig.get().getCharset().displayName());

			if(t.equals(Types.STRING)) {
				if(raw.equals(Types.EMPTY_STRING_TOKEN)) return "";
				if(raw.equals(Types.NULL_TOKEN)) return null;

				return str;
			}
			if(t.equals(Types.INT)) 	return Integer.parseInt(str);
			if(t.equals(Types.LONG)) 	return Long.parseLong(str);
			if(t.equals(Types.SHORT)) 	return Short.parseShort(str);
			if(t.equals(Types.BOOLEAN))	return Boolean.parseBoolean(str);
			if(t.equals(Types.DOUBLE))	return Double.parseDouble(str);
			if(t.equals(Types.FLOAT))	return Float.parseFloat(str);
			if(t.equals(Types.BYTE))	return Byte.parseByte(str);
			if(t.equals(Types.CHAR))	return str.charAt(0);

			return str;
		}
		catch(Exception e) {			
			return enc;
		}
	}
	
	@Override
	public boolean isDecodeable(Type t) {
		return t.equalsAny(Types.STRING, Types.INT, Types.LONG, Types.SHORT, 
				Types.BOOLEAN, Types.DOUBLE, Types.FLOAT, Types.BYTE, Types.CHAR);
	}

}
